package com.macllvm.whale.net;

import android.util.Log;
import java.io.IOException;
import java.lang.Thread;
import java.net.InetSocketAddress;
import java.net.SocketOptions;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.net.MulticastSocket;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.concurrent.ConcurrentLinkedQueue;
import com.macllvm.whale.protocol.ProtocolBase;
import com.macllvm.whale.utils.NetworkTools;



public class UDPClient extends Thread {
    private boolean isRunning = false;
    private DatagramChannel mDatagramChannel;
    private ConcurrentLinkedQueue<Packet> mQueue = new  ConcurrentLinkedQueue<Packet>();

    public UDPClient() throws IOException {
        mDatagramChannel = DatagramChannel.open();
        mDatagramChannel.configureBlocking(false);
        mDatagramChannel.socket().setBroadcast(true);
        mDatagramChannel.socket().setReuseAddress(true);
    }


    public void send(String ip, String data) {
        Packet  packet = new  Packet(ip, data);
        mQueue.add(packet);
    }

    public void close() {
        isRunning = false;
        try {
            if (null != mDatagramChannel && mDatagramChannel.isOpen()) {
                mDatagramChannel.close();
            }
        } catch(IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        isRunning = true;
        try {
            while(isRunning) {
                if(mQueue.size() > 0) {
                    Packet p = mQueue.poll();
                    ByteBuffer byteBuffer = ByteBuffer.wrap(p.data.getBytes());
                    mDatagramChannel.send(byteBuffer, new InetSocketAddress(p.ip, ProtocolBase.IPMSG_PORT));
                }else{
                    Thread.sleep(50);
                }
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    static class Packet {
        String ip;
        String data;

        Packet(String ip, String data) {
            this.ip = ip;
            this.data = data;
        }
    }
}